﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OnlinePharmacyV001.Models;

namespace MvcApplication1.Filters
{
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        OnlinePharmacyEntities db = new OnlinePharmacyEntities();
        public string RequiredPermission;
        //public int YourCustomValue;
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null) throw new ArgumentNullException("httpContext");
            if (HttpContext.Current.Session[Account.SESSION_ID] == null) return false;
            try
            {
                Account account = (Account)HttpContext.Current.Session[Account.SESSION_ID];
                //string delimStr = " ,";
                //char[] delimiter = delimStr.ToCharArray();
                //string[] RoleArray = RequiredRole.Split(delimiter);
                //if (RoleArray.Length > 0 && !RoleArray.Contains(account.Role.rlName))
                //{
                //    return false;
                //}
                List<Permission> permissions = account.Role.Permissions.ToList();
                foreach (Permission per in permissions)
                {
                    if (per.perCode.Equals(RequiredPermission))
                        return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectResult("~/Home");
               
            }

        }
    }
}